import { Service } from 'egg';
import { Topic } from '../model/Topic';

export default class TopicService extends Service {
    /**
     * 查询话题列表
     */
    public async searchTopicList() {
        const resultTopic = await this.ctx.model.Topic.findAll<Topic>({
            attributes: ['topic_id', 'topic_title', 'topic_picture', 'topic_status'],
            where: { is_delete: '1' }
        });
        if (resultTopic.length <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
        }
        return resultTopic;
    }

    /**
     * 新增话题
     * @param param
     */
    public async createTopic(param: any) {
        let submitData: any = {};
        submitData.topic_id = this.ctx.helper.genUUID();
        submitData.topic_title = param.topic_title;
        submitData.topic_picture = param.topic_picture;
        submitData.topic_status = '1';
        submitData.is_delete = '1';
        const resultTopic = await this.ctx.model.Topic.create(submitData);
        if (!resultTopic) {
            throw new Error(JSON.stringify({ code: 2, msg: '新增失败' }));
        }
    }

    /**
     * 修改话题
     * @param param
     */
    public async updateTopic(param: any) {
        const resultTopic = await this.ctx.model.Topic.update(
            { topic_title: param.topic_title, topic_picture: param.topic_picture },
            { where: { topic_id: param.topic_id } }
        );
        if (resultTopic[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '修改失败' }));
        }
    }

    /**
     * 启用、停用话题
     * @param param
     */
    public async startAndStopTopic(param: any) {
        const resultTopic = await this.ctx.model.Topic.update(
            { topic_status: param.type },
            { where: { topic_id: param.topic_id } }
        );
        if (resultTopic[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
        }
    }

}